package cn.aezo.minions.utils;

import cn.aezo.utils.base.StringU;
import cn.aezo.utils.base.ValidU;
import cn.aezo.utils.io.HttpClientU;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WxTemplateMsg {
    @Autowired
    private WxTokenManager wxTokenManager;

    private static String protocolAndDomain;

    private static final String TEMPLATE_MSG_URL =
            "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";

    /**
     * 发送模板消息
     * @param toUserOpenId 目标用户的openid
     * @param templateId 模板消息id
     * @param gotoUrl 跳转地址
     * @param data 模板参数
     */
    public Object sendMsg(String toUserOpenId, String templateId, String gotoUrl, Map data) {
        Object result = null;
        String accessToken = wxTokenManager.getAccessToken();
        if(ValidU.isEmpty(accessToken)) return result;

        String url = String.format(TEMPLATE_MSG_URL, accessToken);

        Map<String, Object> context = new HashMap<>();
        context.put("touser", toUserOpenId);
        context.put("template_id", templateId);
        context.put("url", gotoUrl);
        context.put("data", data);

        String msg = StringU.parseMap2JsonStr(context);

        String str = HttpClientU.httpRequest(url, "POST", msg);
        if(str == null) {
            return null;
        } else {
            try {
                result = StringU.parseJsonStr2Map(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    public String getProtocolAndDomain() {
        return protocolAndDomain;
    }

    @Value("${help.protocolAndDomain}")
    public void setProtocolAndDomain(String protocolAndDomain) {
        this.protocolAndDomain = protocolAndDomain;
    }

    public enum Template {
        PaymentSuccess("DKuKSlWNnYD6XRtgxI_wiGvaI2CEGW-OsMddJN2GzQk", "index.html");

        private String id;
        private String url;

        Template(String id, String url) {
            this.id = id;
            this.url = url;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getUrl() {
            return protocolAndDomain + url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}
